package com.atguigu.spzx.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.h5.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.entity.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;
        //获取缓存对象
        Object cartInfoObj = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));
        CartInfo cartInfo=new CartInfo();
        //有的话给数量加一
        if(cartInfoObj!=null){
            cartInfo= JSON.parseObject(cartInfoObj.toString(),CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum()+skuNum);
            cartInfo.setIsChecked(1);
            cartInfo.setUpdateTime(new Date());
        }else {
            //没有缓存
            //从数据库根据skuId查询添加到购物车的这个商品，封装进cartInfo
            ProductSku productSku = productFeignClient.getBySkuId(skuId);
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
        }
        //把数据存进缓存
        redisTemplate.opsForHash().put(cartKey,String.valueOf(skuId),JSON.toJSONString(cartInfo));
    }

    @Override
    public List<CartInfo> cartList() {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;
        List<Object> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(cartInfoList)){
            List<CartInfo> infoList = cartInfoList.stream().map(cartInfoJSON ->
                    JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());
            return infoList;
        }
        return new ArrayList<>();
    }

    @Override
    public void deleteCart(Long skuId) {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;
        redisTemplate.opsForHash().delete(cartKey,String.valueOf(skuId));
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;

        Boolean hasKey = redisTemplate.opsForHash().hasKey(cartKey, String.valueOf(skuId));
        if(hasKey) {
            String cartInfoJSON = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId)).toString();
            CartInfo cartInfo=JSON.parseObject(cartInfoJSON,CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(cartKey,String.valueOf(skuId),JSON.toJSONString(cartInfo));
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;

        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);
        if(!CollectionUtils.isEmpty(objectList)) {
            objectList.stream().map(cartInfoJSON -> {
                CartInfo cartInfo = JSON.parseObject(cartInfoJSON.toString(), CartInfo.class);
                cartInfo.setIsChecked(isChecked);
                return cartInfo ;
            }).forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey ,
                    String.valueOf(cartInfo.getSkuId()) , JSON.toJSONString(cartInfo)));
        }
    }

    @Override
    public void clearCart() {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> getAllCkecked() {
        //获取当前登录用户的id
        UserInfo userInfo=(UserInfo) AuthContextUtil.get();
        Long userId = userInfo.getId();
        //redis存储时的key
        String cartKey="user:cart:" + userId;
        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);
        if(!CollectionUtils.isEmpty(objectList)) {
            List<CartInfo> cartInfoList = objectList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .collect(Collectors.toList());
            return cartInfoList ;
        }
        return new ArrayList<>() ;
    }
}
